package com.qf.servlet;

import com.qf.entity.Admin;
import com.qf.util.DataUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

/**2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
 * 带头像的注册的Servlet
 *
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@WebServlet(urlPatterns = "/registerfile", loadOnStartup = 8)
public class RegisterFileServlet extends HttpServlet {

    public static String uploaderPath = "D:\\uploader\\";

    public RegisterFileServlet(){
        System.out.println("RegisterFileServlet被加载！");
    }

    /**
     * 注册 - 上传头像
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        //设置文件上传的路径编码格式
        servletFileUpload.setHeaderEncoding("utf-8");

        List<FileItem> items = null;
        try {
            items = servletFileUpload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        //注册用户信息
        Admin admin = new Admin();
        //获得Admin这个类的反射对象（Class对象）
        Class cls = admin.getClass();

        //循环处理各个item项
        if (items != null) {
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //是一个普通项
                    System.out.println("表单项的名称：" + item.getFieldName() + " 值：" + item.getString("utf-8"));

                    if ("birthday".equals(item.getFieldName())) {
                        //特殊处理生日类型
                        admin.setBirthday(item.getString("utf-8"));
                    } else if ("power".equals(item.getFieldName())) {
                        //特殊处理权限类型
                        admin.addPower(item.getString("utf-8"));
                    } else {
                        //其他类型默认交给反射处理
                        //一堆key-value -> Admin对象的对应属性中 ->
                        //item.getFieldName()-username
                        //item.getFieldName()-password
                        try {
                            //getDeclaredField获得私有的成员变量
                            Field field = cls.getDeclaredField(item.getFieldName());
                            field.setAccessible(true);//授权，可以操作私有的成员变量
                            field.set(admin, item.getString("utf-8"));
                        } catch (Exception e) {
                            //e.printStackTrace();
                        }
                    }
                } else {
                    //是一个上传项
                    System.out.println("上传的文件名称：" + item.getName());
                    String filename = UUID.randomUUID().toString();
                    try(  //输入流
                          InputStream in = item.getInputStream();
                          OutputStream out = new FileOutputStream(uploaderPath + filename)
                    ) {
                        //使用工具类 实现文件的拷贝
                        IOUtils.copy(in, out);
                        //将上传的头像名称，关联到用户信息对象中
                        admin.setHeader(filename);
                    }
                }
            }
        }

        //保存用户信息
        DataUtils.addAdmin(admin);
        //重定向到登录页面
        resp.sendRedirect("login.jsp");
    }
}
